package a51qindian.com.comprehensive.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.li.utils.ToastUtil;
import com.li.widget.MultipleLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.activity.FinishInstallActivity;
import a51qindian.com.comprehensive.adapter.TaskInstallAdapter;
import a51qindian.com.comprehensive.base.QDBaseFragment;
import a51qindian.com.comprehensive.items.LinearItemDecoration;
import a51qindian.com.comprehensive.model.BaseModel;
import a51qindian.com.comprehensive.model.TaskInstall;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

import static android.app.Activity.RESULT_OK;

/**
 * Author: Li
 * Date: 2017/9/25 0025
 * Description: 首装任务
 */

public class TaskInstallFragment extends QDBaseFragment {

    public static final String TASK_FIRST_INSTALL = "0";
    public static final String TASK_ADD_INSTALL = "1";
    //1:未接受，2：已完成
    public static final String TASK_UN_ACCEPTED = "1";
    public static final String TASK_FINISHED = "2";
    @BindView(R.id.recycler_task_first_install)
    RecyclerView mRecyclerTaskFirstInstall;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;
    private String mType;
    private String mStatus;
    private List<TaskInstall> mTaskInstallList;
    private TaskInstallAdapter mAdapter;

    private static final int FINISH_INSTALL_CODE=200;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_first_install;
    }

    public static TaskInstallFragment newInstance(String type, String status) {

        Bundle args = new Bundle();
        args.putString("type", type);
        args.putString("status", status);
        TaskInstallFragment fragment = new TaskInstallFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initSth() {
        super.initSth();
        setSmartRefreshLayout(mLayoutRefresh);
        mTaskInstallList = new ArrayList<>();
        mType = getArguments().getString("type");
        mStatus = getArguments().getString("status");
        mRecyclerTaskFirstInstall.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerTaskFirstInstall.addItemDecoration(new LinearItemDecoration());
        mAdapter = new TaskInstallAdapter(mContext, mStatus);
        mRecyclerTaskFirstInstall.setAdapter(mAdapter);
        mAdapter.setOnOpListener(new TaskInstallAdapter.OnOpListener() {
            @Override
            public void onCall(View view, int pos) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + mTaskInstallList.get(pos).getMobile()));
                startActivity(intent);
            }

            @Override
            public void onAccept(View view, final int pos) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext)
                        .setTitle("提示")
                        .setMessage("是否接受该任务")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                acceptTask(mUid, mTaskInstallList.get(pos).getTid(), pos);
                            }
                        });
                builder.create().show();
            }

            @Override
            public void onDone(View view, final int pos) {
                AlertDialog.Builder builder=new AlertDialog.Builder(mContext)
                        .setTitle("提示")
                        .setMessage("是否前往完成该任务")
                        .setNegativeButton("取消",null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent=new Intent(mContext, FinishInstallActivity.class);
                                intent.putExtra("type",mType);
                                intent.putExtra("number",mTaskInstallList.get(pos).getNumber());
                                intent.putExtra("pos",pos);
                                intent.putExtra("tid",mTaskInstallList.get(pos).getTid());
                                intent.putExtra("shopName",mTaskInstallList.get(pos).getShop_name());
                                startActivityForResult(intent,FINISH_INSTALL_CODE);
                            }
                        });
                builder.create().show();
            }
        });
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        showInstallTask(mUid, mType, mStatus, "0");

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        showInstallTask(mUid, mType, mStatus, String.valueOf(mPage + 1));

    }

    @Override
    protected void onCreate() {
        super.onCreate();
        if (mStatus.equals(TASK_UN_ACCEPTED)) {
            showInstallTask(mUid, mType, mStatus, "0");
        }
    }


    @Override
    protected void onFirstVisible() {
        super.onFirstVisible();
        if (!mStatus.equals(TASK_UN_ACCEPTED)) {
            showInstallTask(mUid, mType, mStatus, "0");
        }
    }

    /**
     * 显示 加装|首装 任务
     *
     * @param uid    用户编号
     * @param type   0：首装任务；1：加装任务
     * @param status 0：未接受；1：已接受；2：已完成
     * @param page   页数
     */
    private void showInstallTask(String uid, String type, String status, String page) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("type", type);
        map.put("status", status);
        map.put("page", page);
        ObservableHelper.createObservable(RetrofitCreator.createService().taskInstallList(map))
                .subscribe(new SelectorObserver<BaseModel<List<TaskInstall>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        stopRefreshLoad();
                        mLayoutRefresh.setLoadmoreFinished(true);
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(mContext, info);
                    }

                    @Override
                    protected void onSuccess(BaseModel<List<TaskInstall>> listBaseModel) {
                        List<TaskInstall> taskInstallList = listBaseModel.getData();
                        mLayoutContent.onSuccess();
                        if (mIsRefresh) {
                            mPage = 0;
                            mTaskInstallList.clear();
                        } else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        if (!mIsRefresh && taskInstallList.size() < Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mTaskInstallList.addAll(taskInstallList);
                        mAdapter.setTaskInstallList(mTaskInstallList);
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopRefreshLoad();
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(mContext, e.getMessage());
                    }
                });
    }

    /**
     * 接受任务
     *
     * @param uid 用户编号
     * @param tid 任务编号
     * @param pos 位置  更新界面使用
     */
    private void acceptTask(String uid, String tid, final int pos) {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("tid", tid);
        ObservableHelper.createObservable(RetrofitCreator.createService().acceptInstallTask(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            int code = object.getInt("code");
                            if (code != 1) {
                                ToastUtil.showToast(mContext, object.getString("info"));
                                return;
                            }
                            mTaskInstallList.get(pos).setStatus("1");
                            mAdapter.notifyItemChanged(pos);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(mContext, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }








    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==FINISH_INSTALL_CODE&&resultCode==RESULT_OK) {
            int pos=data.getIntExtra("pos",-1);
            mTaskInstallList.remove(pos);
            mAdapter.notifyItemRemoved(pos);
        }
    }
}
